package gu.doc;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.List;

import com.google.common.collect.ImmutableList;

import gu.doc.ExtClassDoc;
import net.gdface.utils.ClassCommentProvider;

import static gu.doc.JavadocReader.read;

public class ClassCommentProviderImpl implements ClassCommentProvider {
	
	private final ExtClassDoc classDoc;
	private final Class<?> clazz;
	
	public ClassCommentProviderImpl(Class<?> clazz) {
		this.clazz = clazz;
		this.classDoc = read(clazz);
	}

	@Override
	public ImmutableList<String> commentOfClass() {
		if(classDoc  == null){
			return ImmutableList.of();
		}
		List<String> cmt = classDoc.getClassCommentAsList(false,false);
		return cmt  == null ? ImmutableList.<String>of() : ImmutableList.copyOf(cmt);
	}

	@Override
	public ImmutableList<String> commentOfMethod(Method method) {
		if(classDoc  == null){
			return ImmutableList.of();
		}
		List<String> cmt = classDoc.getMethodCommentAsList(method,false,false);
		return cmt  == null ? ImmutableList.<String>of() : ImmutableList.copyOf(cmt);
	}

	@Override
	public ImmutableList<String> commentOfField(String name) {
		if(classDoc  == null){
			return ImmutableList.of();
		}
		List<String> cmt = classDoc.getFieldCommentAsList(name,false,false);
		if(cmt == null){
			try {
				PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name,clazz);
				Method rm = propertyDescriptor.getReadMethod();
				if(rm != null){
					return commentOfMethod(rm);
				}
				Method wm = propertyDescriptor.getWriteMethod();
				if(wm != null){
					return commentOfMethod(wm);
				}
			} catch (IntrospectionException e) {
				// DO NOTHING
			}

		}
		return cmt  == null ? ImmutableList.<String>of() : ImmutableList.copyOf(cmt);
	}

}
